﻿#!/usr/bin/python3
# -*- coding:utf-8 -*-
# @Time         :       2021/8/2 12:21
# @Author       :       林子然
# @File         :       heroes.py
# @Software     :       Pycharm

import requests
import parsel
import pymongo

url = 'http://www.87g.com/zixun/16123.html'
response = requests.get(url)
response.encoding = 'utf-8'

selector = parsel.Selector(text=response.text)


client = pymongo.MongoClient()
db = client['王者荣耀']
collection = db['heroes']

img_infos = selector.xpath('//tr//img')
for img_info in img_infos:
    name = img_info.xpath('./@alt').get()
    name = name.replace('王者荣耀','')
    img_url = img_info.xpath('./@src').get()
    img_content = requests.get(img_url).content
    file_name = name + '.jpg'
    with open('img\\' + file_name,'wb') as f:
        f.write(img_content)
    collection.insert_one({'hero_name':name,
                       'img_url':img_url})
    print('保存完成',file_name)

client.close()